import Vue from 'vue' 
import router from '@/router/router'
import axios from 'axios'
import CONFIG from './config'
import {Toast,Dialog } from "vant"
Vue.use(Toast).use(Dialog);
/* eslint-disable */
function encodeUTF8(s) {
  var i, r = [], c, x;
  for (i = 0; i < s.length; i++)
    if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
    else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
    else {
      if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
        c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
      else r.push(0xE0 + (c >> 12 & 0xF));
      r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    };
  return r;
}

// 字符串加密成 hex 字符串
function sha1(s) {
  var data = new Uint8Array(encodeUTF8(s))
  var i, j, t;
  var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
  s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
  for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
  s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
  s[l - 1] = data.length << 3;
  var w = [], f = [
    function () { return m[1] & m[2] | ~m[1] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; },
    function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; }
  ], rol = function (n, c) { return n << c | n >>> (32 - c); },
    k = [1518500249, 1859775393, -1894007588, -899497514],
    m = [1732584193, -271733879, null, null, -1009589776];
  m[2] = ~m[0], m[3] = ~m[1];
  for (i = 0; i < s.length; i += 16) {
    var o = m.slice(0);
    for (j = 0; j < 80; j++)
      w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
        t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
        m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
    for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
  };
  t = new DataView(new Uint32Array(m).buffer);
  for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);

  var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
    return (e < 16 ? "0" : "") + e.toString(16);
  }).join("");
  return hex;
} 
/* eslint-disable */
// import qs from 'qs'   
const unCheckUrlArr = ["user/updatePerfectInfo","user/getIndustryInfoList","soft/getWapConfig","/soft/getAppConfig"];
axios.defaults.baseURL = CONFIG.api;
axios.defaults.timeout = 8000;
axios.interceptors.request.use((config) => {
  if(config.url.indexOf("getWapConfig")  === -1 && config.url.indexOf("getAppConfig")  === -1 ){
    let _appKey = window.sessionStorage.getItem("appKey" ) ;
    let _jmsz = window.sessionStorage.getItem("jmsz" ) ; 
    if(_appKey && _jmsz){  
      let loadElement = document.getElementById("loadingBox");
      //console.log(loadElement)
      if (loadElement) {
        loadElement.style.display = "none"
      }
    } 
    let timestamp= parseInt(new Date().getTime() / 1000);
    const authAppSecret = "53d094ee4f65d30863285dba3b449f7b" ;
    config.headers['appKey'] =_appKey; 
    config.headers['nonce'] = "tp"+timestamp; 
    config.headers['curTime'] = timestamp; 
    config.headers['checkSum'] = sha1(authAppSecret + _jmsz+ "tp"+timestamp +timestamp);  
  }
  // 1、appKey
  // 2、nonce -- 随机字符串，java的写UUID即可
  // 3、curTime -- 当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
  // 4、checkSum --  生成的方式是：CheckSumBuilder.getCheckSum(authAppSecret + authSaltValue, nonce ,curTime); 
  if(!unCheckUrlArr.includes(config.url)){   
    let ua  = window.navigator.userAgent ;
    let mobileType = (ua.indexOf('Android') > -1||ua.indexOf('Adr') > -1 ) ? 1:0;
    let ua_version = ua.toLowerCase().split("networking gang/")[1];
    let appVersion ;
    let wind_storage = window.localStorage ;
    config.headers['uniqueId'] =wind_storage.platformRole==2 ? wind_storage.uniqueIdByInfluencer : wind_storage.uniqueId;
    if(mobileType){
      appVersion = ua_version? ua_version : "1.0.0";
      config.headers['wapHeader'] = JSON.stringify({ "mobileType":mobileType,"appVersion":appVersion}) ;
    }else{ 
      if(ua_version){
        let ua_info = ua_version.split("/");
        appVersion = ua_info[0]? ua_info[0] : "1.0.0";
        let channelId  = ua_info[1]? ua_info[1] : 1 ; 
        config.headers['wapHeader'] = JSON.stringify({ "mobileType":mobileType,"appVersion":appVersion,"channelId":channelId}) ;
      } 
    }
  } 
  config.headers['Content-Type'] = 'application/json; charset=UTF-8'; 
  return config
}, (err) => {
  return Promise.reject(err);
});

axios.interceptors.response.use((res) => {
  let resData = res.data;
  let otherCodes = [176,177,178,179,180,181,124,200]; 
  if (otherCodes.includes(resData.head.code)) {
    return resData
  } else if (resData.head.code == 110 || resData.head.code == 101 ) {
    let storage_role = window.localStorage.getItem("platformRole") ;
    window.sessionStorage.setItem("appKey" , null) ;
    window.sessionStorage.setItem("jmsz" , null) ;  
    window.sessionStorage.removeItem("appKey");
    window.sessionStorage.removeItem("appKejmszy");
    if(storage_role == 2){
      window.localStorage.setItem("uniqueIdByInfluencer",null);
      window.localStorage.removeItem("uniqueIdByInfluencer");
      Toast(res.data.head.msg);
      setTimeout(() => {
        router.replace("/infLogin/login") ;
      }, 1200);
    }else{
      localStorage.removeItem("uniqueId");
      Toast(res.data.head.msg);
      setTimeout(() => {
        router.go(-1) ;
      }, 1200);
    } 
    return Promise.reject(res);
  } else {
    Toast(res.data.head.msg);
    return Promise.reject(res);
  }
}, (err) => { 
  Dialog.alert({
    message:"抱歉，请求超时！<br/>是否重新刷新页面？",
    messageAlign: "center",
    cancelButtonColor: "#303133",
    confirmButtonColor: "#FF2525",
    closeOnPopstate: true
  }).then(()=>{
    window.location.reload();
  })
  return Promise.reject(err);
});

export default axios;


